package com.cloudptt.api.product.func.sys.fsm;

import com.cloudptt.api.product.func.call.CallConst;
import com.cloudptt.api.product.func.sys.SysFunc;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.timer.IRollback;
import com.cloudptt.api.product.timer.RollbackTimer;

import android.content.Context;

public class HttpAuthingState implements ISysState,IRollback {

	private SysAgent sysAgent = null;
	private RollbackTimer rollbackTimer = null;
	private boolean isRelogin = false;

	private int retryCount = 3;

	public HttpAuthingState(Context ctx,SysAgent sysAgent,boolean isRelogin)
	{
		Log.d(SysFunc.Log_Key, "HttpAuthingState isRelogin = " + isRelogin);
		this.sysAgent = sysAgent;
		this.rollbackTimer = new RollbackTimer(0,10,this);
		this.isRelogin = isRelogin;
	}
	@Override
	public int doSysAction(int sysAction) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void recevSysMsg(int sysMsg) {
		// TODO Auto-generated method stub
		Log.d(SysFunc.Log_Key, "HttpAuthingState recevSysMsg sysMsg = " + sysMsg);
		if(SysConst.SysMsg_Svr_Stop == sysMsg)
		{
			this.sysAgent.goToState(SysStateInfo.SysState_SvrStopState,SysStateInfo.Cause_Suc);
		}
		else if(sysMsg == SysConst.SysMsg_Http_Auth_Suc)
		{
			sysAgent.goToState(SysStateInfo.SysState_HttpAuthSucState,SysStateInfo.Cause_Suc);
		}
		else if(!isRelogin && sysMsg == SysConst.SysMsg_Http_Auth_Failed)
		{
			sysAgent.goToState(SysStateInfo.SysState_SvrStartState,SysStateInfo.Cause_Failed);
		}
		else if(!isRelogin && sysMsg == SysConst.SysMsg_Http_Auth_Timeout)
		{
			sysAgent.goToState(SysStateInfo.SysState_SvrStartState,SysStateInfo.Cause_Timeout);
		}
		else if(SysConst.SysMsg_Logout == sysMsg)
		{
			this.sysAgent.doSipUnAuth();
			this.sysAgent.goToState(SysStateInfo.SysState_SvrStartState,SysStateInfo.Cause_Logout);
		}
	}

	@Override
	public int getState() {
		// TODO Auto-generated method stub
		return SysStateInfo.SysState_HttpAuthingState;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		if(rollbackTimer != null)
		{
			rollbackTimer.cancelTimer();
			rollbackTimer = null;
		}
		sysAgent = null;
	}
	@Override
	public void rollback(int timerId) {
		// TODO Auto-generated method stub
		Log.d(SysFunc.Log_Key, SysStateInfo.stateTag(this.getState()) + " rollback retryCount = " + retryCount);
		if(this.isRelogin
			&& retryCount > 0)
		{
			if(sysAgent != null)
			{
				sysAgent.doHttpAuth();
			}
			if(rollbackTimer != null)
			{
				rollbackTimer.restartTimer(30);
			}
			retryCount --;
		}
		else {
			this.sysAgent.doSipUnAuth();
			this.sysAgent.goToState(SysStateInfo.SysState_SvrStartState, SysStateInfo.Cause_Timeout);
		}
	}

}
